<?php

namespace App\Services\Api;

use Curl;

/**
 * 调用JAVA接口数据所适用到的类
 *  $obj = new Api();
 *  $apiCode = 'D#50001';
 *  $data = [];
 *  $postData = $obj->getJavaPostData($apiCode, $data);
 *  $result = $obj->getJavaResponseData($postData);
 */
class Api
{
    public $apiKey = 'DIxsZd1zuX1m2q30G2ZT6GRd8HVUaBff';
    public $apiSource = 'tanwin';
    public $apiU = 'tw';

    public function getJavaResponseData($postData)
    {
        try {
            $objResponse = Curl::to(env('JAVA_API_URL'))
                ->withOption('TIMEOUT', 20)
                ->withData($postData)
                ->post();
            apiLog($postData);
            $arrResponse = json_decode($objResponse, true);
            if (!is_array($arrResponse)) {
                $message = 'request time out';
                errorLog($postData, $message);
                return false;
            }
            if (isset($arrResponse['error_number']) && $arrResponse['error_number'] != 0) {
                $message = 'api return error_number:' . $arrResponse['error_number'] . '--error_msg:' . $arrResponse['error_msg'];
                errorLog($postData, $message);
                return false;
            }
            return $arrResponse['res_data'];
        } catch (\Exception $e) {
            exceptionLog($e);
            return false;
        }
    }

    public function getJavaCeilData($apiCode, $ceilCode)
    {
        try {
            $postData = $this->assembleRequestData($apiCode, time(), ['no' => $ceilCode]);
            $objResponse = Curl::to(env('CMS_API_URL'))
                ->withOption('TIMEOUT', 20)
                ->withData($postData)
                ->post();
            apiLog($postData);
            $arrResponse = json_decode($objResponse, true);
            return $arrResponse['res_data'];
        } catch (\Exception $e) {
            exceptionLog($e);
            return false;
        }
    }

    public function getPhpServiceResponseData($postData)
    {
        try {
            $objResponse = Curl::to(env('PHP_SERVICE_API_URL'))
                ->withOption('TIMEOUT', 20)
                ->withData($postData)
                ->post();
            apiLog($postData);
            $arrResponse = json_decode($objResponse, true);
            if (!$arrResponse['result']) {
                return false;
            }
            return true;
        } catch (\Exception $e) {
            exceptionLog($e);
            return false;
        }
    }

    public function getJavaPostData($apiCode, $postData, $source = '')
    {
        $apiCodeClass = $this->_getApiCodeClass($apiCode);
        $classPath = '\App\Services\Api\\';
        if (!class_exists($classPath . $apiCodeClass)) {
            echo 'api code class not exits';
            exit;
        }
        $class = new \ReflectionClass($classPath . $apiCodeClass);
        $funcList = $class->newInstance();
        $initPostData = $funcList->getInitPostData($postData);
        $initApiCode = $funcList->getInitApiCode();

        return $this->assembleRequestData($initApiCode, time(), $initPostData, $source);
    }

    protected function assembleRequestData($apiCode, $time, $postData, $source = '')
    {
        $source = $this->getApiSource();
        $token = $this->getApiToken($apiCode, $time);
        $jsonReqData = $this->getJsonReqData($postData);
        return
            [
            'source' => $source,
            'app_id' => $apiCode,
            'token' => $token,
            'timestamp' => $time,
            'req_data' => $jsonReqData,
            'u' => $this->apiU,
        ];
    }

    public function getPhpServicePostData($apiCode, $postData)
    {
        $apiCodeClass = $this->_getApiCodeClass($apiCode);
        $classPath = '\App\Services\Api\\';
        if (!class_exists($classPath . $apiCodeClass)) {
            echo 'api code class not exits';
            exit;
        }
        $class = new \ReflectionClass($classPath . $apiCodeClass);
        $funcList = $class->newInstance();
        $initPostData = $funcList->getInitPostData($postData);
        $initApiCode = $funcList->getInitApiCode();
        return $this->assemblePhpServiceRequestData($initApiCode, $initPostData);
    }

    public function assemblePhpServiceRequestData($apiCode, $postData)
    {
        return [
            'app_id' => $apiCode,
            'req_data' => json_encode($postData),
        ];
    }

    protected function getApiSource($source = '')
    {
        return $source ? $source : $this->apiSource;
    }

    protected function getApiToken($apiCode, $time)
    {
        return md5($apiCode . $time . $this->apiKey);
    }

    protected function getJsonReqData($postData = '')
    {
        return $postData ? json_encode($postData) : '{}';
    }

    private function _getApiCodeClass($apiCode)
    {
        if (strpos($apiCode, '-')) {
            return str_replace('#', '', str_replace('-', '', $apiCode));
        } else {
            return implode('', explode('#', $apiCode));
        }
    }

}
